import { ObjectId } from 'mongodb'
import * as db from '../db'
import { stats } from '../stats'
import { DingdanStat, Relevance } from '../types'
import { addSome, removeSome, checkSome } from './tools'

// 添加评论
export async function addRemark(value: any, userId: ObjectId) {
  const { bookId, dingdanId, content, rate, confirm } = value
  if (dingdanId) {
    const dingdan = await db.dingdansCollection.findOne({
      _id: new ObjectId(dingdanId),
      userId
    })
    if (!dingdan) throw stats.ERR_NOT_RIGHT
  }
  const obj = {
    userId,
    bookId: new ObjectId(bookId),
    content,
    rate,
    thumbs: 0,
    isDelete: false,
    createAt: Date.now()
  }
  const res = await db.remarksCollection.insertOne({ _id: null, ...obj })
  if (res.insertedId) {
    await addSome(userId, res.insertedId, Relevance.Remark)
  }
  const user = await db.userCollection.findOne(
    { _id: userId },
    { projection: { avatar: 1, nickname: 1 } }
  )
  return {
    _id: res.insertedId,
    ...obj,
    user
  }
}

// 处理点赞
export async function dealthumb(value: any, userId: ObjectId) {
  const { remarkId, flag } = value
  const other = new ObjectId(remarkId)
  const res = await checkSome(userId, other, Relevance.likeRemark)
  if (flag) {
    if (res) return '已点赞'
    await addSome(userId, other, Relevance.likeRemark)
    return '点赞成功'
  } else {
    await removeSome(userId, other, Relevance.likeRemark)
    return '取消点赞'
  }
}

// 确认收货,取消订单
export async function confirm(value: any, userId: ObjectId) {
  const { dingdanId, flag } = value
  const _id = new ObjectId(dingdanId)
  const confirm = flag ? DingdanStat.Queren : DingdanStat.Cancel
  const res = await checkSome(userId, _id, Relevance.Dingdan)
  if (res) {
    const dingRes = await db.dingdansCollection.findOneAndUpdate(
      { _id },
      { $set: { confirm } }
    )
    return dingRes.value
  }
}

// 评论列表 -> rate == 0的是留言, 不等于0的才是评论,
export async function list(value: any, userId?: ObjectId) {
  const { bookId, skip, limit, flag } = value
  const obj = flag ? { rate: { $gt: 0 } } : { rate: 0 }
  const bookid = new ObjectId(bookId)
  const total = await db.remarksCollection
    .find({ bookId: bookid, ...obj, isDelete: false })
    .count()
  const list = await db.remarksCollection
    .aggregate([
      { $match: { bookId: bookid, ...obj, isDelete: false } },
      {
        $lookup: {
          from: 'user',
          localField: 'userId',
          foreignField: '_id',
          as: 'user'
        }
      },
      { $sort: { thumbs: 1 } },
      { $skip: skip },
      { $limit: limit },
      { $unwind: '$user' },
      {
        $project: {
          rate: 1,
          thumbs: 1,
          content: 1,
          createAt: 1,
          user: {
            _id: 1,
            nickname: 1,
            avatar: 1
          }
        }
      }
    ])
    .toArray()
  if (userId) {
    for (const item of list) {
      const res = await Promise.all([
        checkSome(userId, item._id, Relevance.likeRemark),
        db.connectCollection
          .find({ userId, destId: item._id, type: Relevance.likeRemark })
          .count()
      ])
      const [islove, thumbs] = [!!res[0], res[1]]
      item.islove = islove
      item.thumbs = thumbs
    }
    return { list, total }
  }
  return { list, total }
}
